package com.search.examples;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.search.tools.CaffeineTool;
import com.search.tools.MD5EncryptTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class FangShanSearch {

    private  static  String url = "https://apps.jiatu.cloud/client/book/search";
    private  static String entityStr = "{\"libcode\":\"fangshanqu\",\"channel\":\"yuntu-wx-mini\",\"timestamp\":shijian,\"salt\":448928,\"sign\":\"qianming\",\"bizParam\":{\"pageNo\":1,\"pageSize\":15,\"keyword\":\"shuhao\",\"holdingStatus\":0,\"searchType\":1}}";

    /*private static JSONObject entity;


    static {
        entity = new JSONObject();

    }*/

    public static void main(String[] args) throws UnsupportedEncodingException {
        //post("url");
    }
    //0没书 1有书 -1有书被别人借走了 -2返回数据结构异常
    public static int search(String isbn){

        JSONObject result = post(isbn);
        if(null!=result){
            int code = result.getInteger("code");
            boolean isSuccess = result.getBoolean("success");
            if(isSuccess && 0==code){
                JSONObject data = result.getJSONObject("data");
                if(null!=data){
                    int total = data.getInteger("total");
                    log.debug("搜索到数量"+total);
                    if(total>1){
                        log.debug("怎么这么多"+result.toString());
                    }
                    JSONArray jsonArray = data.getJSONArray("books");
                    if(null!=jsonArray && jsonArray.size()>0){
                        JSONObject book = (JSONObject) jsonArray.get(0);
                        int holding = book.getInteger("availableNumber");
                        if(holding>0){
                            return 1;
                        }else {
                            return -1;
                        }

                    }else {
                        return 0;
                    }
                }else{
                    return -2;
                }
            }
        }else {
            return -2;
        }

        return -2;
    }

    public static JSONObject post(String isbn)  {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNo",1);
        jsonObject.put("pageSize",15);
        jsonObject.put("keyword",isbn);
        jsonObject.put("holdingStatus",0);
        jsonObject.put("searchType",1);

        List<String> keys = new ArrayList<>(jsonObject.keySet());
        Collections.sort(keys);

        // 使用LinkedHashMap来保持顺序
        LinkedHashMap<String, Object> orderedMap = new LinkedHashMap<>();
        for (String key : keys) {
            orderedMap.put(key, jsonObject.get(key));
        }

        // 将LinkedHashMap转换为JSONObject（注意：这里只是模拟，因为fastjson2可能不直接支持）
        // 你可能需要以字符串的形式输出，或者再次使用JSON.parseObject(JSON.toJSONString(orderedMap), JSONObject.class)转换回JSONObject
        JSONObject sortedJsonObject = JSON.parseObject(JSON.toJSONString(orderedMap), JSONObject.class);

        String time = System.currentTimeMillis()+"";

        String originalString = sortedJsonObject.toJSONString()+time+"a8fdad21e5c9ef44aa96e6df1404e811";

        String sign = MD5EncryptTool.encry(originalString);
        String entity = entityStr.replace("shuhao",isbn).replace("shijian",time).replace("qianming",sign);

        CaffeineTool.setSign(entity);

        /*entity.put("keyword",isbn);
        entity.put("pageNo","1");
        entity.put("pageSize","12");
        entity.put("publisher","");
        entity.put("author","");
        entity.put("subject","");
        entity.put("classno","");
        entity.put("days","");
        entity.put("language","");
        entity.put("pubdate","");
        entity.put("holdingStatus","0");
        entity.put("matchType","0");
        entity.put("subLibcode","");*/
        HttpResponse response ;
        JSONObject result=null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000) // 连接超时时间，单位毫秒
                .setSocketTimeout(50000)  // 读取超时时间，单位毫秒
                .build();
        post.setConfig(requestConfig);
        post.setHeader("Sec-Fetch-Dest","empty");
        post.setHeader("clientinfo","{\"appId\":\"\",\"channel\":\"yuntu-wx-mini\",\"libcode\":\"fangshanqu\"}");
        post.setHeader("Sec-Fetch-Site","cross-site");
        post.setHeader("Host","apps.jiatu.cloud");
        post.setHeader("Accept","*/*");
        post.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b19)XWEB/9193");
        post.setHeader("xweb_xhr","1");
        post.setHeader("jwt","");
        post.setHeader("Accept-Language","zh-CN,zh;q=0.9");
        post.setHeader("Accept-Encoding","gzip, deflate, br");
        post.setHeader("Sec-Fetch-Mode","cors");
        post.setHeader("Content-Type","application/json");
        post.setHeader("Referer","https://servicewechat.com/wx09fbb5f91edae820/37/page-frame.html");
        post.setHeader("Connection","keep-alive");

       /* String jsonString =entity.toString();
        try {
            StringEntity stringEntity = new StringEntity(jsonString);
        } catch (UnsupportedEncodingException e) {
            log.error("请求体编码错误"+e.getMessage());
            return result;
        }*/
        //stringEntity.setContentType("application/json");
        //post.setEntity(stringEntity);
        post.setEntity(new StringEntity(entity, ContentType.APPLICATION_JSON));


        try{
            response = httpclient.execute(post);
            String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            result = JSONObject.parseObject(body);
            //System.out.println(result);
            log.info(isbn+"搜索结果"+result.toString());

        }catch (Exception e){
            log.error("请求图书馆接口出错"+e.toString());
            e.printStackTrace();
        }


        return result;
    }


}
